

function setCookieFromResponseHeaders(setCookieHeader, referer){
    const cookiesArray = setCookieHeader.split(', ');
    cookiesArray.forEach(cookie => {
        const [keyValue, ...options] = cookie.split('; ');
        const [key, ...values] = keyValue.split('=');
        if (key && values.length>0){
            const newKeyValue = `${key}=${values.join('=')}`;
            try {
                if (global.document) {
                    document.cookie = newKeyValue;
                } else {
                    global.cookieJar.setCookieSync(newKeyValue, referer);
                }
            } catch (e) {
                debugger;
            }
        }
    });
}

function setCookieFrom(respHeaders, url) {
    if (respHeaders && respHeaders['set-cookie']) {
        for (let i = 0; i < respHeaders['set-cookie'].length; i++) {
            setCookieFromResponseHeaders(respHeaders['set-cookie'][i], url)
        }
    }
}

function setCookieStr(cookieStr, url) {
    cookieStr.split('; ').forEach(cookie => {
        setCookieFromResponseHeaders(cookie, url);
    })
}

module.exports = {
    setCookieFromResponseHeaders: setCookieFromResponseHeaders,
    setCookieFrom: setCookieFrom,
    setCookieStr: setCookieStr
}
